﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Train.Code;

namespace Train
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //获取验证码
        const string strUrl = @"http://www.gz.gov.cn/sofpro/gecs/common/image.jsp?dt=Thu%20Nov%2024%202011%2017:20:21%20GMT+0800%20(China%20Standard%20Time)";

        //全局bit
        Bitmap bit = null;

        //2个工具类
        PictureTool pictureTool = null;
        GetStringInPictureTool GSIP = null;


        //所有的按钮
        //List<Button> lstbtn = null;

        #region 所有控件方法

        /// <summary>
        /// 窗口初始化
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            pictureTool = new PictureTool();
            GSIP = new GetStringInPictureTool();
            HbitmapList = new List<IntPtr>();
        }

        /// <summary>
        /// 获取验证码图片按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetPIN_Click(object sender, RoutedEventArgs e)
        {
            bit = GetSourceCode(strUrl);
            ShowImg(bit);

        }

        /// <summary>
        /// 载入图片按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadImage_Click(object sender, RoutedEventArgs e)
        {
            if (HbitmapList != null && HbitmapList.Count > 0)
            {
                foreach (IntPtr obj in HbitmapList)
                {
                    MemoryTool.DeleteObject(obj);
                }
            }

            LoadImg();

            //结束GC一下
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        //去色按钮
        private void btn_ClearImg_Click(object sender, RoutedEventArgs e)
        {
            if (bit == null)
                return;

            asyncValue.Text = "图片去色中...";

            //异步开启去色
            AsyncHandle(clearHandleMethod);
        }

        //灰白按钮
        private void btn_grayImg_Click(object sender, RoutedEventArgs e)
        {
            if (bit_NOTCLEAR == null)
                return;

            asyncValue.Text = "图片灰白中...";
            AsyncHandle(grayHandleMethod);
        }

        //二进制按钮
        private void btn_binarySystemImg_Click(object sender, RoutedEventArgs e)
        {
            if (bit_GRAY == null)
                return;

            asyncValue.Text = "图片二进制中...";
            AsyncHandle(binaryzationHandleMethod);
        }

        //深度1并保存按钮（因为速度较快，就懒得异步了）
        private void btn_save1bitImg_Click(object sender, RoutedEventArgs e)
        {
            save1bit();
        }

        //图文识别按钮
        private void btn_GetStringInPng_Click(object sender, RoutedEventArgs e)
        {
            asyncValue.Text = "图片识别中...";
            GetString();
        }

        //原始图片
        private void ImageBox_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ShowImgOnWindow(bitSource);
        }
        //去色图片
        private void ImageBox_ClearColor_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ShowImgOnWindow(bitSource_CLEAR);
        }
        //灰白图片
        private void ImageBox_Gray_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ShowImgOnWindow(bitSource_GRAY);
        }
        //二进制图片
        private void ImageBox_binaryzation_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ShowImgOnWindow(bitSource_binaryzation);
        }

        #endregion

        #region 载入图片
        /// <summary>
        /// 载入图片
        /// </summary>
        private void LoadImg()
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Multiselect = true;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件夹";
                dialog.Filter = "图像文件(*.jpg;*.jpg;*.jpeg;*.gif;*.png)|*.jpg;*.jpeg;*.gif;*.png";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileStream fs = File.OpenRead(dialog.FileName); //OpenRead
                    int filelength = 0;
                    filelength = (int)fs.Length; //获得文件长度 
                    Byte[] image = new Byte[filelength]; //建立一个字节数组 
                    fs.Read(image, 0, filelength); //按字节流读取 
                    Image result = Image.FromStream(fs);
                    bit = new Bitmap(result);
                    result.Dispose();
                    fs.Dispose();

                    ShowImg(bit);
                }
            }
        }
        #endregion

        #region 从网站获取验证码图片
        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <param name="url">获取验证码图片链接</param>
        /// <returns></returns>
        private Bitmap GetSourceCode(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream st = response.GetResponseStream();
            Bitmap bitmap = (Bitmap)Bitmap.FromStream(st);
            st.Close();

            return bitmap;
        }
        #endregion

        #region 在Image控件显示图片
        /// <summary>
        /// 显示图片
        /// </summary>
        BitmapSource bitSource;
        BitmapSource bitSource_CLEAR;
        BitmapSource bitSource_GRAY;
        BitmapSource bitSource_binaryzation;
        private void ShowImg(object bitmap)
        {
            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate ()
            {
                if (bitmap is Bitmap)
                {
                    Bitmap bit = bitmap as Bitmap;
                    if (bit == this.bit)
                        bitShow(ImageBox, ref bitSource, bit);
                    else if (bit == bit_NOTCLEAR)
                        bitShow(ImageBox_ClearColor, ref bitSource_CLEAR, bit);
                    else if (bit == bit_GRAY)
                        bitShow(ImageBox_Gray, ref bitSource_GRAY, bit);
                    else if (bit == bit_binaryzation)
                        bitShow(ImageBox_binaryzation, ref bitSource_binaryzation, bit);
                }
            });
        }
        //bitmapSource缓存list
        List<IntPtr> HbitmapList;
        /// <summary>
        /// 在image显示图片
        /// </summary>
        /// <param name="imagebox">要显示的image控件</param>
        /// <param name="bitSource">要赋值的bitSource文件</param>
        /// <param name="bit">主要的bit文件</param>
        void bitShow(System.Windows.Controls.Image imagebox, ref BitmapSource bitSource, Bitmap bit)
        {
            IntPtr f = bit.GetHbitmap();
            HbitmapList.Add(f);
            bitSource = Imaging.CreateBitmapSourceFromHBitmap(f, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            imagebox.Source = bitSource;
        }
        #endregion

        #region 图片的各种处理
        //去色bitmap
        Bitmap bit_NOTCLEAR;
        /// <summary>
        /// 去色处理
        /// </summary>
        /// <returns></returns>
        private string clearHandleMethod()
        {
            bit_NOTCLEAR = pictureTool.imgdo(bit);
            ShowImg(bit_NOTCLEAR);

            return "OK";
        }


        //灰白bit
        Bitmap bit_GRAY;
        /// <summary>
        /// 灰白处理
        /// </summary>
        /// <returns></returns>
        private string grayHandleMethod()
        {
            bit_GRAY = pictureTool.Gray(bit_NOTCLEAR);
            ShowImg(bit_GRAY);

            return "OK";
        }

        //二进制bit
        Bitmap bit_binaryzation;
        /// <summary>
        /// 二进制处理
        /// </summary>
        /// <returns></returns>
        private string binaryzationHandleMethod()
        {
            bit_binaryzation = pictureTool.binaryzation(bit_GRAY);
            ShowImg(bit_binaryzation);

            return "OK";
        }
        #endregion

        #region 保存图片
        /// <summary>
        /// 1bit保存
        /// </summary>
        void save1bit()
        {
            using (SaveFileDialog saveDlg = new SaveFileDialog())
            {
                Bitmap curBitmap = pictureTool.ConvertTo24bppTo1bpp(bit_binaryzation);
                if (bit_binaryzation == null)
                    return;
                saveDlg.Title = "保存为";
                saveDlg.OverwritePrompt = true;
                saveDlg.Filter =
                    "BMP文件 (*.bmp) | *.bmp|" +
                    "Gif文件 (*.gif) | *.gif|" +
                    "JPEG文件 (*.jpg) | *.jpg|" +
                    "PNG文件 (*.png) | *.png";
                saveDlg.ShowHelp = true;
                if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string fileName = saveDlg.FileName;
                    string strFilExtn = fileName.Remove(0, fileName.Length - 3);
                    switch (strFilExtn)
                    {
                        case "bmp":
                            curBitmap.Save(fileName, ImageFormat.Bmp);
                            break;
                        case "jpg":
                            curBitmap.Save(fileName, ImageFormat.Jpeg);
                            break;
                        case "gif":
                            curBitmap.Save(fileName, ImageFormat.Gif);
                            break;
                        case "tif":
                            curBitmap.Save(fileName, ImageFormat.Tiff);
                            break;
                        case "png":
                            curBitmap.Save(fileName, ImageFormat.Png);
                            break;
                        default:
                            break;
                    }
                }
                if (curBitmap == null)
                {
                    return;
                }
            }
            
        }
        #endregion

        #region 图文识别
        /// <summary>
        /// 图文识别
        /// </summary>
        OpenFileDialog dialog = null;
        private void GetString()
        {
            dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "图像文件(*.jpg;*.jpg;*.jpeg;*.gif;*.png;*.bmp)|*.jpg;*.jpeg;*.gif;*.png;*.bmp";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //异步处理图文识别
                AsyncHandle(GetStringInPng);
                dialog.Dispose();
            }
        }
        //异步得到的字符串
        string text = "";
        private string GetStringInPng()
        {
            text = GSIP.GetStringClearError(dialog.FileName);
            return "OK";
        }
        #endregion

        #region Async异步
        /// <summary>
        /// 异步处理
        /// </summary>
        private void AsyncHandle(Func<string> Method)
        {
            //异步任务封装
            Func<string> asyncAction = Method;

            //异步完成返回值
            Action<IAsyncResult> resultHandler = delegate (IAsyncResult asyncResult)
            {
                string result = asyncAction.EndInvoke(asyncResult);
                asyncValue.Text = result;

                if (text != "")
                {
                    tbx_Image.Text = text;
                }
            };

            //异步回调
            AsyncCallback asyncActionCallback = delegate (IAsyncResult asyncResult)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Background, resultHandler, asyncResult);
            };

            //在UI线程中开始异步任务
            asyncAction.BeginInvoke(asyncActionCallback, null);
        }
        #endregion

        #region 点击图片处理
        //显示放大图片的窗口
        public static SHOWIMG_WINDOWS imgWindow = null;
        //比例缩放使用数组
        Dictionary<string, int> bitWH;
        //打开窗口，显示大图
        private void ShowImgOnWindow(BitmapSource bitSource)
        {
            if (imgWindow != null)
                imgWindow.Close();

            if (bitSource == null)
                return;

            if (imgWindow == null)
                imgWindow = new SHOWIMG_WINDOWS();

            bitWH = pictureTool.AdjustSize(Screen.PrimaryScreen.Bounds.Width - 100, Screen.PrimaryScreen.Bounds.Height - 100, Convert.ToInt32(bitSource.Width), Convert.ToInt32(bitSource.Height));
            imgWindow.Width = bitWH["Width"];
            imgWindow.Height = bitWH["Height"];

            imgWindow.MasterImage.Source = bitSource;
            imgWindow.Show();
        }
        #endregion

        #region 获取所有按钮
        //暂时没做，下版本再更新
        #endregion
    }
}